//定义用户相关的仓库
import {ref} from "vue";
import {defineStore} from "pinia";
import {reqCode, reqPhoneLogin} from "../../api/hospital";
import {LoginData, UserInfo} from "../../api/hospital/type.ts";
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from "../../utils/user.ts";

const useUserStore = defineStore('User', () => {
  //控制登陆框显示与影藏
  const visiable = ref<boolean>(false)

  const code = ref<string>('')
  const getCode = async (phone: string) => {

    const result = await reqCode(phone)
    if (result.code === 200) {
      code.value = result.data
      return 'ok';
    }
    return Promise.reject(new Error(result.message))

  }

  const userInfo = ref<UserInfo>(JSON.parse(GET_TOKEN()))

  const phoneLogin = async (loginData: LoginData) => {

    const result = await reqPhoneLogin(loginData)
    if (result.code === 200) {
      userInfo.value = result.data
      SET_TOKEN(JSON.stringify(result.data))
      return 'ok';
    }
    return Promise.reject(new Error(result.message))

  }
  const logout = () => {
    userInfo.value = {name: "", token: ""}
    REMOVE_TOKEN()
  }

  return {
    visiable,
    getCode,
    code,
    userInfo,
    phoneLogin,
    logout,
  }
})
export default useUserStore
